#!/usr/bin/env python3
# Created by han on 2016/7/4
import socketserver
import subprocess

class Hftp(socketserver.BaseRequestHandler):

    def handle_outer(self, func):
        def handle_inner():
            self.request.send(bytes("欢迎使用Hftp", "utf8"))
            while True:
                data = self.request.recv(1024)  # 接受客户端发来的命令
                # print(data,len(data))
                if len(data) == 0:
                    break
                print("[%s] input: %s" % (self.client_address, data.decode()))
                client_data = data.decode()
                if client_data.startswith("get") or client_data.startswith("put"):
                    pass
                else:
                    self.handle(data)
        return handle_inner

    @handle_outer
    def handle(self, data):
            data = self.request.recv(1024)          #接受客户端发来的命令
            # print(data,len(data))
            if len(data) == 0:
                return False
            print("[%s] input: %s" % (self.client_address, data.decode()))
            cmd_data = subprocess.Popen(data.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
            ret = cmd_data.stdout.read()  #python3 中默认返回的就是bytes类型
            if not ret:
                ret = cmd_data.stderr.read()
            if len(ret) == 0:
                ret = bytes("cmd has output", "utf8")

            try:
                ready_data = "ready|%d" % len(ret)
                print(ready_data)
                self.request.sendall(bytes(ready_data, "utf8"))

                client_ready = self.request.recv(1024)

                print('-----client_ready',client_ready.decode())
                if client_ready.decode().startswith("start"):
                    self.request.sendall(ret)
            except Exception as ex:
                print(ex,type(ex))
                self.request.sendall(bytes(ex, "utf8"))


if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(("0.0.0.0", 8899), Hftp)
    server.serve_forever()